package com.hmtech.aup.presentation.ui

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.credentials.CredentialManager
import androidx.credentials.CustomCredential
import androidx.credentials.GetCredentialRequest
import androidx.credentials.GetCredentialResponse
import androidx.credentials.exceptions.GetCredentialException
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.common.SignInButton
import com.google.android.libraries.identity.googleid.GetGoogleIdOption
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
import com.google.android.libraries.identity.googleid.GoogleIdTokenParsingException
import com.hmtech.aup.R
import com.hmtech.aup.domain.dto.GoogleSignInDTO
import com.hmtech.aup.domain.vo.SaTokenInfoVO
import com.hmtech.aup.network.RetrofitClient
import com.hmtech.aup.util.TokenUtils
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MyFragment : Fragment() {
    companion object {
        private const val TAG = "AvatarFragment"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        var view = inflater.inflate(R.layout.fragment_my, container, false)
        view.findViewById<SignInButton>(R.id.btn_signin_with_google).setOnClickListener {
            signInWithGoogle()
        }
        return view
    }

    private fun signInWithGoogle() {
        viewLifecycleOwner.lifecycleScope.launch {
            for (filter in listOf(true, false)) {
                val googleIdOption: GetGoogleIdOption = GetGoogleIdOption.Builder()
                    .setFilterByAuthorizedAccounts(filter)
                    .setServerClientId(getString(R.string.ayp_server_client_id))
                    .setAutoSelectEnabled(true)
                    .build()
                val request: GetCredentialRequest = GetCredentialRequest.Builder()
                    .addCredentialOption(googleIdOption)
                    .build()
                val credentialManager = CredentialManager.Companion.create(requireContext())
                try {
                    val result = credentialManager.getCredential(
                        context = requireContext(),
                        request = request
                    )
                    handleSignIn(result)
                    break
                } catch (e: GetCredentialException) {
                    Toast.makeText(
                        requireContext(),
                        "未检测到可用账号，请手动登录",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }

    suspend fun signInServerWithGoogle(idToken: String) {
        try {
            val dto = GoogleSignInDTO(idToken)
            val response = RetrofitClient.userApiService.signInWithGoogle(dto)  // 直接调用 suspend 函数
            val tokenValue = response.tokenValue
            if (tokenValue != null) {
                TokenUtils.saveTokenToLocal(requireContext(), tokenValue)
                showToast(getString(R.string.login_success))
            }
        } catch (e: Exception) {
            showToast(getString(R.string.login_fail) + e.message)
            TokenUtils.deleteTokenInLocalStorage(requireContext())
        }
    }

    fun refreshUI() {
        TokenUtils.getTokenFromLocal(requireContext())
    }

    fun showToast(text: String) {
        Toast.makeText(requireContext(), text, Toast.LENGTH_SHORT).show()
    }

    fun handleSignIn(result: GetCredentialResponse) {
        val credential = result.credential
        when (credential) {
            is CustomCredential -> {
                if (credential.type == GoogleIdTokenCredential.Companion.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {
                    try {
                        val tokenCredential = GoogleIdTokenCredential.Companion
                            .createFrom(credential.data)
                        viewLifecycleOwner.lifecycleScope.launch {
                            signInServerWithGoogle(tokenCredential.idToken)
                        }
                        Log.i(TAG, "googleIdTokenCredential: $tokenCredential")
                        Log.i(TAG, "googleIdTokenCredential.idToken: $tokenCredential.idToken")
                    } catch (e: GoogleIdTokenParsingException) {
                        Log.e(TAG, "Received an invalid google id token response", e)
                    }
                } else {
                    // Catch any unrecognized custom credential type here.
                    Log.e(TAG, "Unexpected type of credential")
                }
            }
        }
    }
//                }
//                try {
//                    // Use googleIdTokenCredential and extract the ID to validate and
//                    // authenticate on your server.
//                    val googleIdTokenCredential = GoogleIdTokenCredential
//                        .createFrom(credential.data)
//                    Log.i(TAG, "googleIdTokenCredential: $googleIdTokenCredential")
////                        // You can use the members of googleIdTokenCredential directly for UX
////                        // purposes, but don't use them to store or control access to user
////                        // data. For that you first need to validate the token:
////                        // pass googleIdTokenCredential.getIdToken() to the backend server.
////                        GoogleIdTokenVerifier verifier = ... // see validation instructions
////                        GoogleIdToken idToken = verifier.verify(idTokenString);
////                        // To get a stable account identifier (e.g. for storing user data),
////                        // use the subject ID:
////                        idToken.getPayload().getSubject()
//                } catch (e: GoogleIdTokenParsingException) {
//                    Log.e(TAG, "Received an invalid google id token response", e)
//                }
//            } else {
//                // Catch any unrecognized custom credential type here.
//                Log.e(TAG, "Unexpected type of credential")
//            }
//                }
//

//        }
//    }

}